package cn.sailing.plugins.position;

import android.Manifest;
import android.content.Context;
import android.util.Log;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.getcapacitor.JSObject;
import com.getcapacitor.PermissionState;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.annotation.Permission;
import com.getcapacitor.annotation.PermissionCallback;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.navix.api.NavigatorConfig;
import com.tencent.navix.api.NavigatorZygote;
import com.tencent.tencentmap.mapsdk.maps.TencentMapInitializer;
import com.tencent.trackx.api.TrackerXCreator;

import java.util.Objects;

@CapacitorPlugin(
        name = "Position",
        permissions = {
                @Permission(
                        alias = "location",
                        strings = {
                                Manifest.permission.ACCESS_COARSE_LOCATION,
                                Manifest.permission.ACCESS_WIFI_STATE,
                                Manifest.permission.CHANGE_WIFI_STATE,
                                Manifest.permission.ACCESS_NETWORK_STATE,
                                Manifest.permission.CHANGE_NETWORK_STATE,
                                Manifest.permission.FOREGROUND_SERVICE,
                        }
                ),
        }
)
public class PositionPlugin extends Plugin {

    private TrackService service;

    private IPusher pusher;
    private String TrackId;

    private Context context;

    private AMapLocationClient amap_client;
    private AMapLocationClientOption amap_options;

//    private LocationClient baidu_client;
//    private LocationClientOption baidu_options;

    TencentLocationManager tencent_client;
    TencentLocationListener tencent_listener;
    TencentLocationRequest tencent_request;

    ITrackListener listener = new ITrackListener() {
        @Override
        public void onTerminalCreated() {

        }

        @Override
        public void onTrackCreated() {

        }
    };

    @Override
    public void load() {
        super.load();
        Log.i(getLogTag(), "---------------------加载----------------------");
        context = getBridge().getActivity().getApplicationContext();
//        LocationClient.setAgreePrivacy(true);
        pusher = (lng, lat, acc, speed, direction, type) -> {
            Log.i(getLogTag(), "定位成功:\t" + type + "\tLNG:\t" + lng + "\tLAT:\t" + lat);
            JSObject result = new JSObject();
            long now = System.currentTimeMillis();
            result.put("creation_time", now);
            result.put("latitude", lat);
            result.put("longitude", lng);
            result.put("accuracy", acc);
            result.put("speed", speed);
            result.put("direction", direction);
            result.put("type", type);
            result.put("track_id", TrackId);
            notifyListeners("position", result);
        };
    }

    @PermissionCallback
    private void positionPermissionCallback(PluginCall call) {

        if (getPermissionState("location") != PermissionState.GRANTED) {
            Log.i("权限检测回调", getPermissionState("location") + "");
            startPosition(call);
        } else {
            call.reject("权限被拒绝");
        }
    }

    @PermissionCallback
    private void trackPermissionCallback(PluginCall call) {
        if (getPermissionState("location") == PermissionState.GRANTED) {
            Log.i("权限检测回调", getPermissionState("location") + "");
            startTrackService(call);
        } else {
            call.reject("权限被拒绝");
        }
    }

    @PluginMethod
    public void StartPosition(PluginCall call) {
        if (getPermissionState("location") != PermissionState.GRANTED) {
            requestPermissionForAlias("location", call, "positionPermissionCallback");
        } else {
            Log.i("权限检测", getPermissionState("location") + "");
            startPosition(call);
        }
    }

    @PluginMethod
    public void PausePosition(PluginCall call) {
//        baidu_client.stop();
        amap_client.stopLocation();
        tencent_client.removeUpdates(tencent_listener);
        call.resolve();
    }


    @PluginMethod
    public void StopPosition(PluginCall call) {
        TrackId = "";
//        baidu_client.stop();
        amap_client.stopLocation();
        tencent_client.removeUpdates(tencent_listener);
        call.resolve();
    }


    @PluginMethod
    public void StartTrackService(PluginCall call) {
        if (getPermissionState("location") != PermissionState.GRANTED) {
            requestPermissionForAlias("location", call, "trackPermissionCallback");
        } else {
            Log.i("权限检测", getPermissionState("location") + "");
            startTrackService(call);
        }
    }

    @PluginMethod
    public void StopTrackService(PluginCall call) {
        if (service != null) {
            service.StopTrack();
        }
        call.resolve();
    }

    public void startTrackService(PluginCall call) {
        Log.i(getLogTag(), "---------------------开始记录轨迹----------------------");
        if (service == null) {
            service = new TrackService();
            service.Init(context, listener);
        }
        service.StartTrack();
        call.resolve();
    }

    private void startPosition(PluginCall call) {
        Log.i(getLogTag(), "---------------------开始定位----------------------");
        if (TrackId == null || TrackId.isEmpty()) {
            TrackId = System.currentTimeMillis() + "";
        }
        StartAMapPosition();
        StartBaiduMapPosition();
        StartTencentPosition();
        call.resolve();
    }


    private void notifyPosition(double lng, double lat, double acc, String type) {
        Log.i(getLogTag(), "定位成功:\t" + type + "\tLNG:\t" + lng + "\tLAT:\t" + lat);
        JSObject result = new JSObject();
        long now = System.currentTimeMillis();
        result.put("creation_time", now);
        result.put("latitude", lat);
        result.put("longitude", lng);
        result.put("accuracy", acc);
        result.put("type", type);
        result.put("track_id", TrackId);
        notifyListeners("position", result);
    }


    private void StartAMapPosition() {
        try {
            if (amap_client == null) {
                amap_client = new AMapLocationClient(context);
                amap_options = new AMapLocationClientOption();
                amap_options.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                amap_options.setInterval(2000);
                amap_options.setNeedAddress(false);
                amap_client.setLocationOption(amap_options);
                amap_client.setLocationListener(location -> {
                    notifyPosition(location.getLongitude(), location.getLatitude(), location.getAccuracy(), "amap");
                });
            }
            amap_client.startLocation();
        } catch (Exception e) {
            Log.e("定位", Objects.requireNonNull(e.getLocalizedMessage()));
            JSObject result = new JSObject();
            result.put("message", e.getLocalizedMessage());
            notifyListeners("error", result);
        }
    }

    private void StartBaiduMapPosition() {
//        try {
//            if (baidu_client == null) {
//                baidu_client = new LocationClient(context);
//                baidu_options = new LocationClientOption();
//                baidu_options.setCoorType("gcj02");
//                baidu_options.setScanSpan(2000);
//                baidu_options.setNeedDeviceDirect(true);
//                baidu_options.setIgnoreKillProcess(true);
//                baidu_options.setIsNeedLocationPoiList(true);
//                baidu_options.setIsNeedAltitude(false);
//                baidu_options.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//                baidu_options.setLocationNotify(true);
//                baidu_options.setOpenGnss(true);
//                baidu_options.setIsEnableBeidouMode(true);
//                baidu_client.setLocOption(baidu_options);
//                baidu_client.registerLocationListener(new BDAbstractLocationListener() {
//                    @Override
//                    public void onReceiveLocation(BDLocation location) {
//                        notifyPosition(location.getLongitude(), location.getLatitude(), location.getAcc(), "baidu");
//                    }
//                });
//            }
//            baidu_client.start();
//        } catch (Exception e) {
//            JSObject result = new JSObject();
//            result.put("message", e.getLocalizedMessage());
//            notifyListeners("error", result);
//        }
    }

    private void StartTencentPosition() {
//        if (tencent_client == null) {
//            tencent_client = TencentLocationManager.getInstance(context);
//            tencent_request = TencentLocationRequest.create();
//            tencent_request.setInterval(2000);
//            tencent_request.setAllowGPS(true);
//            tencent_request.setLocMode(TencentLocationRequest.HIGH_ACCURACY_MODE);
//            tencent_request.setGpsFirst(true);
//            tencent_listener = new TencentLocationListener() {
//                @Override
//                public void onLocationChanged(TencentLocation location, int error, String s) {
//                    if (error == TencentLocation.ERROR_OK) {
//                        notifyPosition(location.getLongitude(), location.getLatitude(), location.getAccuracy(), "tencent");
//                    }
//                }
//
//                @Override
//                public void onStatusUpdate(String s, int i, String s1) {
//
//                }
//            };
//        }
//        tencent_client.requestLocationUpdates(tencent_request, tencent_listener);
    }

}
